import React, { Component } from 'react';
import { Grid, Button, Input } from 'semantic-ui-react';
import BusiCrumb from '../../../menu/crumb/BusiCrumb';
import { Map, TileLayer, FeatureGroup } from 'react-leaflet';
import L from "leaflet";
import { EditControl } from 'react-leaflet-draw';
import axios from 'axios';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './MapEditShow.css';

delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
    iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0/images/marker-icon.png',
    iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0/images/marker-icon.png',
    shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0/images/marker-shadow.png',
});

class MapAddCity extends Component{

    constructor() {
        super();
        this.state = {
            cityname : ""
        }
    }

    _onEdited = (e) => {
        let numEdited = 0;
        e.layers.eachLayer( (layer) => {
            numEdited += 1;
        });
        console.log('_onEdited: edited ' + numEdited + ' layers', e);
        this._onChange();
    }
    
    _onCreated = (e) => {
        let type = e.layerType;
        // let layer = e.layer;
        if (type === 'marker') {
            // Do marker specific actions
            console.log("_onCreated: marker created", e);
        }
        else {
            console.log("_onCreated: something else created:", type, e);
        }
        // Do whatever else you need to. (save to db; etc)
        this._onChange();
    }
    
    _onDeleted = (e) => {
        let numDeleted = 0;
        e.layers.eachLayer( (layer) => {
          numDeleted += 1;
        });
        console.log('onDeleted: removed '+  numDeleted + 'layers', e);
        this._onChange();
    }
    
    _onMounted = (drawControl) => {
        console.log('_onMounted', drawControl);
    }
    
    _onEditStart = (e) => {
        console.log('_onEditStart', e);
    }
    
    _onEditStop = (e) => {
        console.log('_onEditStop', e);
    }
    
    _onDeleteStart = (e) => {
        console.log('_onDeleteStart', e);
    }
    
    _onDeleteStop = (e) => {
        console.log('_onDeleteStop', e);
    }

    render() {
        return (
            <Grid>
                <Grid.Row>
                    <Grid.Column>
                        <BusiCrumb></BusiCrumb>
                    </Grid.Column>
                </Grid.Row>
                <Grid.Row>
                    <Grid.Column>
                        <Map style={{ width: '100%', height: '500px' }} center={[20, 121]} zoom={3} zoomControl={true}>
                            <TileLayer attribution='&copy;OpenStreetMap contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"/>
                            <FeatureGroup ref={ (reactFGref) => {this._onFeatureGroupReady(reactFGref);} }>
                                <EditControl
                                    position='topright'
                                    onEdited={this._onEdited}
                                    onCreated={this._onCreated}
                                    onDeleted={this._onDeleted}
                                    onMounted={this._onMounted}
                                    onEditStart={this._onEditStart}
                                    onEditStop={this._onEditStop}
                                    onDeleteStart={this._onDeleteStart}
                                    onDeleteStop={this._onDeleteStop}
                                    draw={{
                                        rectangle: false,
                                        polyline: false,
                                        polygon: false,
                                        circle: false,
                                        circlemarker: false
                                    }} />
                            </FeatureGroup>
                        </Map>
                    </Grid.Column>
                </Grid.Row>
                <Grid.Row>
                    <Grid.Column>
                        <Input label="City Name" placeholder='input city name' ref={input => this.inputtext = input} required/>
                    </Grid.Column>
                </Grid.Row>
                <Grid.Row>
                    <Grid.Column>
                        <Button primary onClick={this.handleClick.bind(this)} >Update</Button>
                    </Grid.Column>
                </Grid.Row>
            </Grid>
        );
    }

    _editableFG = null

    _onFeatureGroupReady = (reactFGref) => {
        // populate the leaflet FeatureGroup with the geoJson layers
        let leafletGeoJSON = new L.GeoJSON();
        let leafletFG = reactFGref.leafletElement;

        leafletGeoJSON.eachLayer( (layer) => {
            leafletFG.addLayer(layer);
        });

        // store the ref for future access to content
        this._editableFG = reactFGref;
    }

    _onChange = () => {
        // this._editableFG contains the edited geometry, which can be manipulated through the leaflet API
        const { onChange } = this.props;

        if (!this._editableFG || !onChange) {
            return;
        }
        const geojsonData = this._editableFG.leafletElement.toGeoJSON();
        onChange(geojsonData);
    }

    handleMessage(e){
        this.setState({
            cityname: e.target.value
        });
    }

    handleClick(e) {
        if (this._editableFG && this._editableFG.leafletElement) {
            const geojson = this._editableFG.leafletElement.toGeoJSON();
            if (geojson.features.length > 0) {
                axios.post("/api/cities", {
                    name: this.inputtext.inputRef.current.value,
                    geometry: geojson.features[0].geometry
                },{
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.usertoken
                        }
                    }).then(res => {
                        toast.info("City添加成功...", {
                            autoClose: 1000,
                            draggable: false,
                            closeButton: false,
                            position: toast.POSITION.TOP_CENTER,
                            onClose: () => this._editableFG.leafletElement.clearLayers()
                        });
                    }).catch(err => {
                        toast.error("City名称重复...", {
                            autoClose: 1000,
                            draggable: false,
                            closeButton: false,
                            position: toast.POSITION.TOP_CENTER
                        });
                });
            }
        }
    }
}
export default MapAddCity;